#include "registerdialog.h"
#include "ui_registerdialog.h"
#include <QRegExpValidator>

RegisterDialog::RegisterDialog(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RegisterDialog)
    , m_dbManager(new DatabaseManager(this))
{
    ui->setupUi(this);
    
    // 设置窗口属性：保留标准窗口外观，不使用透明与无边框
    setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground, false);
    
    // 设置窗口标题
    setWindowTitle("用户注册");
    
    // 连接信号和槽
    connect(ui->usernameEdit, &QLineEdit::returnPressed, this, &RegisterDialog::on_usernameEdit_returnPressed);
    connect(ui->passwordEdit, &QLineEdit::returnPressed, this, &RegisterDialog::on_passwordEdit_returnPressed);
    connect(ui->confirmPasswordEdit, &QLineEdit::returnPressed, this, &RegisterDialog::on_confirmPasswordEdit_returnPressed);
    
    // 设置用户名输入框的验证器（只允许字母、数字和下划线）
    QRegExp usernameRegex("[a-zA-Z0-9_]{3,20}");
    ui->usernameEdit->setValidator(new QRegExpValidator(usernameRegex, this));
    
    // 设置焦点到用户名输入框
    ui->usernameEdit->setFocus();
    
    // 检查数据库连接
    if (!m_dbManager->isConnected()) {
        showError("数据库连接失败，请检查系统配置！");
    }
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::keyPressEvent(QKeyEvent *event)
{
    // 处理ESC键退出
    if (event->key() == Qt::Key_Escape) {
        close();
    }
    QWidget::keyPressEvent(event);
}

void RegisterDialog::on_registerButton_clicked()
{
    // 获取输入的用户名和密码
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();
    QString confirmPassword = ui->confirmPasswordEdit->text();
    
    // 验证注册信息
    if (validateRegistration(username, password, confirmPassword)) {
        // 创建新用户
        if (createUser(username, password)) {
            showSuccess("注册成功！请返回登录界面进行登录。");
            clearInputs();
            // 发出注册成功信号，让登录窗口恢复显示
            emit registrationSucceeded();
            close();
        } else {
            showError("注册失败，请稍后重试！");
        }
    }
}

void RegisterDialog::on_cancelButton_clicked()
{
    close();
}

void RegisterDialog::on_usernameEdit_returnPressed()
{
    // 用户名输入框回车，焦点移到密码框
    ui->passwordEdit->setFocus();
}

void RegisterDialog::on_passwordEdit_returnPressed()
{
    // 密码输入框回车，焦点移到确认密码框
    ui->confirmPasswordEdit->setFocus();
}

void RegisterDialog::on_confirmPasswordEdit_returnPressed()
{
    // 确认密码输入框回车，触发注册
    on_registerButton_clicked();
}

bool RegisterDialog::validateRegistration(const QString &username, const QString &password, const QString &confirmPassword)
{
    // 验证用户名
    if (!validateUsername(username)) {
        return false;
    }
    
    // 验证密码
    if (!validatePassword(password)) {
        return false;
    }
    
    // 验证确认密码
    if (password != confirmPassword) {
        showError("两次输入的密码不一致！");
        ui->confirmPasswordEdit->clear();
        ui->confirmPasswordEdit->setFocus();
        return false;
    }
    
    // 检查用户名是否已存在
    if (m_dbManager->isUsernameExists(username)) {
        showError("用户名已存在，请选择其他用户名！");
        ui->usernameEdit->clear();
        ui->usernameEdit->setFocus();
        return false;
    }
    
    return true;
}

bool RegisterDialog::validateUsername(const QString &username)
{
    if (username.isEmpty()) {
        showError("请输入用户名！");
        ui->usernameEdit->setFocus();
        return false;
    }
    
    if (username.length() < 3 || username.length() > 20) {
        showError("用户名长度必须在3-20个字符之间！");
        ui->usernameEdit->setFocus();
        return false;
    }
    
    // 检查用户名是否只包含字母、数字和下划线
    QRegExp usernameRegex("[a-zA-Z0-9_]{3,20}");
    if (!usernameRegex.exactMatch(username)) {
        showError("用户名只能包含字母、数字和下划线！");
        ui->usernameEdit->setFocus();
        return false;
    }
    
    return true;
}

bool RegisterDialog::validatePassword(const QString &password)
{
    if (password.isEmpty()) {
        showError("请输入密码！");
        ui->passwordEdit->setFocus();
        return false;
    }
    
    if (password.length() < 6 || password.length() > 20) {
        showError("密码长度必须在6-20个字符之间！");
        ui->passwordEdit->setFocus();
        return false;
    }
    
    return true;
}

void RegisterDialog::showError(const QString &message)
{
    QMessageBox::critical(this, "错误", message, QMessageBox::Ok);
}

void RegisterDialog::showSuccess(const QString &message)
{
    QMessageBox::information(this, "成功", message, QMessageBox::Ok);
}

void RegisterDialog::clearInputs()
{
    ui->usernameEdit->clear();
    ui->passwordEdit->clear();
    ui->confirmPasswordEdit->clear();
    ui->usernameEdit->setFocus();
}

bool RegisterDialog::createUser(const QString &username, const QString &password)
{
    // 创建新用户对象
    User newUser(0, username, password, QDateTime::currentDateTime());
    
    // 添加到数据库
    return m_dbManager->addUser(newUser);
}
